package com.example.demomk.Fragment;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demomk.Adapter.MeasurementAdapter;
import com.example.demomk.Interface.OnBottomBarListener;
import com.example.demomk.Interface.OnDialogButtonClickListener;
import com.example.demomk.MainActivity;
import com.example.demomk.R;
import com.example.demomk.Repository.printRepository;
import com.example.demomk.Utils.CustomDialog;
import com.example.demomk.Utils.Dialogprint;
import com.example.demomk.Utils.PDFPageBuilder;
import com.example.demomk.Utils.StdDialog;
import com.example.demomk.Utils.StdDialogData;
import com.example.demomk.Utils.TimeUtils;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.ViewModel.PrintViewModel;
import com.example.demomk.databinding.FragmentHomeBinding;
import com.example.demomk.db.AppDatabase;
import com.example.demomk.entity.AvgMeasurement;
import com.example.demomk.entity.AvgMeasurementWithDetails;
import com.example.demomk.entity.AvgMeasurementWithMeasurements;
import com.example.demomk.entity.LocationStats;
import com.example.demomk.entity.Measurement;
import com.example.demomk.entity.SizeStats;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class HomeFragment extends  Fragment {
    private static final Logger log = LoggerFactory.getLogger(HomeFragment.class);
    private FragmentHomeBinding binding;
    private MeasurementAdapter adapter;
    private RecyclerView recyclerView;
    private  String currentTime;
    private MeasurementViewModel viewModel;
    private PrintViewModel printViewModel;
    private Context context;
    private CustomDialog dialogs;
    //打印dialog框
    private Dialogprint dialogPrint;
    //stddialog框
    private StdDialog stdDialog;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    //自定义字体
    private Typeface font;

    private int currentPage;

    private String title = "默认报告";
    //采样设置信息

    private String[][] thresholdData = {
            {"报警水平", "——", "——", "——", "——", "——", "——"},
            {"行动限", "3520.0", "——", "——", "——", "20.0", "——"}
    };

    private String[] allCounts = {"总体平均值", "标准差", "标准误差", "95%UCL", "最大值", "局部最大平均值"};


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private String timestamp;


    public HomeFragment() {

    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentHomeBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = requireContext();
        initView();
        if(font == null){
            font =  Typeface.createFromAsset(context.getAssets(), "fonts/SourceHanSerifCN-ExtraLight.ttf");
        }
        // 设置点击事件
        binding.rule.setOnClickListener(v -> {
            RuleFragment  fragment = new RuleFragment();
            loadFragment(fragment);
        });


        TextView dataText = binding.dataText;
        dataText.setSelected(true);

        //我是dev文件
        adpaterEvent();
        //我是master
        bottomOnclick();

        //插入用户等等
//        binding.insert.setOnClickListener(v -> {
//            addNewMeasurement();
////            viewModel.insertUser(new User("研发部", TimeUtils.getCurrentTime()));
////            viewModel.insertLocation(new Location("Default", "N/A"));
//            Toast.makeText(context, "Successful!", Toast.LENGTH_SHORT).show();
//        });

        //插入测试数据
//        binding.insertdemo.setOnClickListener(v -> {
//            int userId = 2;
//            int locationId = 3;
//
//            viewModel.isExist(userId, locationId).observe(getViewLifecycleOwner(), count -> {
//                if (count == 0) {
//                    AvgMeasurement avgMeasurement = new AvgMeasurement(userId, locationId, currentTime, 100.0,"测试", "ISO2015-1:652");
//                    viewModel.insertAvgMeasurement(avgMeasurement);
//                    Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(requireContext(), "该用户已存在", Toast.LENGTH_SHORT).show();
//                }
//            });
//
//        });

    }


    //初始化view
    private void initView() {
        viewModel = new ViewModelProvider(this).get(MeasurementViewModel.class);
        printViewModel = new ViewModelProvider(this).get(PrintViewModel.class);
        recyclerView =  binding.recyclerView;
        adapter = new MeasurementAdapter();
        recyclerView.setAdapter(adapter);

        recyclerView.setLayoutManager(new LinearLayoutManager(context));

        // 设置分割线（可选）
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        int color = ContextCompat.getColor(context, R.color.blue);
        divider.setDrawable(new ColorDrawable(color));
        recyclerView.addItemDecoration(divider);

        // 观察数据并更新列表
        viewModel.getAllAvgMeasurements().observe(getViewLifecycleOwner(), avgMeasurements -> {
            adapter.setMeasurements(avgMeasurements);
        });

        currentTime = TimeUtils.getCurrentTime();

    }
    private void bottomOnclick() {
        //点击事件
        if (requireActivity() instanceof OnBottomBarListener) {
            ((MainActivity) requireActivity()).setHomeButtonListener(v -> {
//                List<AvgMeasurementWithDetails> selectedMeasurements = adapter.getSelectedMeasurements();
            });
        }
        //管理按钮
        if (requireActivity() instanceof OnBottomBarListener) {
            ((MainActivity) requireActivity()).setManageButtonListener(v -> {

                dialogs = new CustomDialog(requireContext(), new OnDialogButtonClickListener() {
                    @Override
                    public void onConfirm(int start_page, int end_page) {
                        stdDialog = new StdDialog(requireContext(), new OnDialogButtonClickListener() {

                            @Override
                            public void onConfirm(int start_page, int end_page) {

                            }
                            @Override
                            public void onCancel(int start_page, int end_page, String message, StdDialogData data) {
                                viewModel.getAvgMeasurementById(start_page).observe(getViewLifecycleOwner(), avgMeasurements -> {
                                    if (avgMeasurements != null && !avgMeasurements.isEmpty()) {
                                        for (AvgMeasurement avg : avgMeasurements) {
                                            // 模拟同步加载数据
                                            viewModel.calculateStatsForAvgAsync(avg, statsList -> {
                                                viewModel.getLocationStatsByAvgId(start_page).observe(getViewLifecycleOwner(), pdfStatus -> {
                                                    if (pdfStatus == null) {
                                                        return;
                                                    }
                                                    printViewModel.generatePDF(requireContext(), message, start_page, new printRepository.OnPDFGeneratedListener() {
                                                        @Override
                                                        public void onSuccess(File file) {
                                                            //子线程，非UI线程
                                                            Log.d("PDF", "PDF 已生成：" + file.getName());
                                                        }
                                                        @Override
                                                        public void onError(Exception e) {
                                                            Toast.makeText(context, "生成失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                        }
                                                    },font,data,statsList,pdfStatus);
                                                });
                                            });
                                        }
                                    }
                                });

                            }
                        },requireActivity(),  start_page);
                        stdDialog.show();
                    }
                    @Override
                    public void onCancel(int start_page, int end_page, String message,  StdDialogData data) {

                    }
                }, currentPage, "STD");
                dialogs.show();
            });
        }


        //打印按钮
        if (requireActivity() instanceof OnBottomBarListener) {
            ((MainActivity) requireActivity()).setPrintButtonListener(v -> {

                List<AvgMeasurementWithDetails> selectedMeasurements = adapter.getSelectedMeasurements();
                if (!selectedMeasurements.isEmpty()) {
                    List<Integer> selectedIds = new ArrayList<>();
                    for (AvgMeasurementWithDetails item : selectedMeasurements) {
                        selectedIds.add(item.getId());
                    }

                    dialogPrint = new Dialogprint(requireContext(), new OnDialogButtonClickListener() {
                        @Override
                        public void onConfirm(int start_page, int end_page) {
                            // 处理确认逻辑
                        }
                        @Override
                        public void onCancel(int start_page, int end_page, String message, StdDialogData data) {
                            title = message;
                            // 获取选中 ID 列表
                            // 批量打印
                            generateMultiplePDFs(selectedIds);

                        }
                    }, selectedIds, requireActivity());

                    dialogPrint.show();
                }else {
                    // 没有选中项，加载 CustomDialog
                    dialogs = new CustomDialog(requireContext(), new OnDialogButtonClickListener() {
                        @Override
                        public void onConfirm(int start_page, int end_page) {
                            List<Integer> selectedId = new ArrayList<>();
                            for (int i = start_page; i <= end_page; i++) {
                                selectedId.add(i);
                            }
                            // 确定打印的dialog框
                            dialogPrint = new Dialogprint(requireContext(), new OnDialogButtonClickListener() {
                                @Override
                                public void onConfirm(int start_page, int end_page) {
                                    // 处理确认逻辑
                                }
                                @Override
                                public void onCancel(int start_page, int end_page, String message, StdDialogData data) {
                                    title = message;
                                    //导出pdf
                                    generateMultiplePDFs(selectedId);
                                }
                            }, selectedId, requireActivity());
                            dialogPrint.show();
                        }

                        @Override
                        public void onCancel(int start_page, int end_page, String message,  StdDialogData data) {
                            // 处理取消逻辑
                        }
                    }, currentPage,  "数据导出");

                    dialogs.show();
                }
            });
        }
    }

    //加载列表信息
    private void adpaterEvent() {
        //监听事件
        adapter.setOnItemSelectedListener((position, isChecked) -> {
            // 检查是否所有 item 都被选中
            boolean allSelected = true;
            for (Boolean selected : adapter.getSelectedItems()) {
                if (!selected) {
                    allSelected = false;
                    break;
                }
            }

            binding.checkAll.setChecked(allSelected);
            binding.currentAll.setChecked(allSelected);
        });

        //点击全选
        binding.checkAll.setOnClickListener(v -> {
            boolean isChecked = binding.checkAll.isChecked();
            adapter.selectAll(isChecked);
            binding.currentAll.setChecked(isChecked); // 同步更新 currentAll
        });

        //当前页全选
        binding.currentAll.setOnClickListener(v -> {
            boolean isChecked = binding.currentAll.isChecked();
            adapter.selectAll(isChecked);
            binding.checkAll.setChecked(isChecked); // 同步更新 checkAll
        });

        viewModel.getMeasurementCount().observe(requireActivity(), count -> {
            if (count != null) {
                binding.count.setText("样本数: "+String.valueOf(count));
            }
        });

        adapter.setOnItemClickListener((position, id) -> {
            DetailsFragment detailsFragment = DetailsFragment.newInstance(id);
            loadFragment(detailsFragment);
        });
        //查询总数
        viewModel.getAvgMeasurementCount().observe(requireActivity(), count -> {
            if (count != null) {
                currentPage = count;
            }
        });

    }

    //生成多pdf文件
    public void generateMultiplePDFs(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            Toast.makeText(context, "没有可打印的数据", Toast.LENGTH_SHORT).show();
            return;
        }

        for (int avgId : ids) {
            viewModel.getAvgMeasurementById(avgId).observe(this, avgMeasurements -> {
                if (avgMeasurements != null && !avgMeasurements.isEmpty()) {
                    for (AvgMeasurement avg : avgMeasurements) {
                        // 模拟同步加载数据
                        viewModel.calculateStatsForAvgAsync(avg, statsList -> {
//                            sizeStats = statsList;//多个粒径的计算值
                            // 设置当前处理的 avgMeasure 和 location
                            viewModel.getAvgMeasurementWithDetails(avgId).observe(this, avgMeasurementWithMeasurements -> {
                                if (avgMeasurementWithMeasurements != null) {
//                                    avgMeasure = avgMeasurementWithMeasurements;
//                                    location = avgMeasurementWithMeasurements.location;
                                    // 重新计算 stats
                                    viewModel.getLocationStatsByAvgId(avgId).observe(this, pdfStatus -> {
                                        if (pdfStatus == null) {
//                                            stats = pdfStatus;
                                            return;
                                        }
                                        // 生成 PDF
                                        File file = printPDF(avgMeasurementWithMeasurements,pdfStatus,statsList); // 使用 id 区分文件名
                                        if (file != null) {
                                            Log.d("PDFPrint", "已生成 PDF: " + file.getName());
                                        }else {
                                            Log.d("PDFPrint", "生成 PDF 失败");
                                        }
                                    });
                                }
                            });
                        });
                    }
                }
            });
        }
    }

    //打印pdf文件
    private File  printPDF(AvgMeasurementWithMeasurements avgMeasure,
                           List<LocationStats> stats,
                           List<SizeStats> sizeStats)  {

        if (avgMeasure == null  || stats == null || sizeStats == null) {
            Toast.makeText(context, "数据未准备好，请稍后再试", Toast.LENGTH_SHORT).show();
            return null;
        }

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();




        // 2. 跟踪当前Y坐标位置
        float currentY = 0;

        // 3. 绘制各部分内容
        currentY = drawHeader(canvas, pageInfo, currentY);
        currentY = drawReportTitle(canvas, currentY);
        currentY = drawDeviceInfo(canvas, pageInfo, currentY);
        currentY =  drawReportContent(canvas, currentY,avgMeasure);
        currentY =  drawAdditionalContent(canvas,  currentY,stats);
        currentY =  drawStatsTable(canvas,  currentY,avgMeasure,sizeStats,stats);
        drawpagefooter(canvas,pageInfo,  currentY, avgMeasure);


        document.finishPage(page);

        //导出文件的名字
        timestamp = TimeUtils.formatTimeString(avgMeasure.avgMeasurement.getStartTime());
        String  fileName = "Data Report1_A2400074_"  + avgMeasure.location.getName() + "_"+ timestamp+".pdf";
        File file = new File(context.getExternalFilesDir(null), fileName);

        try {
            document.writeTo(new FileOutputStream(file));
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            document.close();
        }
    }
    //绘制页脚
    private void drawpagefooter(Canvas canvas,PdfDocument.PageInfo pageInfo, float currentY,AvgMeasurementWithMeasurements avgMeasure) {
        Paint paint = createPaint(10, Color.BLACK, false);
        paint.setTextSize(10);
        float textHeight = pageInfo.getPageHeight() - 60;
        float Signature = textHeight - 20; // 页面底部签名区域的位置

        canvas.drawText("操作员:", 270, Signature , paint);
        canvas.drawLine(315, Signature , 395, Signature , paint);

        canvas.drawText("审核员:", 420, Signature , paint);
        canvas.drawLine(465, Signature , 550, Signature , paint);


        canvas.drawLine(50, textHeight, 550, textHeight, paint);

        String create =  "Created by:  "+ avgMeasure.user.getName() + "   "+currentTime;
        canvas.drawText(create, 50, textHeight+15, paint);

        String text = "page: 1";
        float textWidth = paint.measureText(text);
        float textX = pageInfo.getPageWidth() - 50 - textWidth;
        canvas.drawText(text, textX, textHeight+15, paint);
    }

    //绘制阈值、统计分析表格等
    private float drawStatsTable(Canvas canvas, float startY,AvgMeasurementWithMeasurements avgMeasure,List<SizeStats> statsList,List<LocationStats> stats) {
        Paint paint = createPaint(10, Color.BLACK, false);
        paint.setTypeface(font);
        paint.setFakeBoldText(true);
        canvas.drawText("阈值", 50, startY + 15, paint);

        paint.setTextSize(8);
        paint.setFakeBoldText(false);
        String text = "计数单位  ∑/m³";
        float textWidth = paint.measureText(text);
        float textX = 525 - textWidth;
        canvas.drawText(text, textX, startY + 15, paint);
        startY += 20;
        // 表格标题
        String[] headerTitles = {"", "0.5μm", "1.0μm", "2.0μm", "3.0μm", "5.0μm", "10μm"};
        float[] columnWidths = {100, 65, 65, 65, 65, 65, 65}; // 每列的宽度

        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, startY, 50 + sum(columnWidths), startY + 17, paint); // 画表头背景
        // 表头文本颜色
        paint.setColor(Color.BLACK);

        PDFPageBuilder pdfPageBuilder = new PDFPageBuilder(canvas, paint);

        float y = pdfPageBuilder.drawTable(50, startY, headerTitles, thresholdData, columnWidths);

        paint.setTextSize(10);
        paint.setFakeBoldText(true);
        canvas.drawText("统计分析", 50, y + 20, paint);

        paint.setTextSize(8);
        paint.setFakeBoldText(false);
        canvas.drawText(text, textX, y + 20, paint);

        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, y + 25, 50 + sum(columnWidths), y + 42, paint); // 画表头背景
        paint.setColor(Color.BLACK);
        String[][] data = convertToTableData(statsList, allCounts);
        float SecondY = pdfPageBuilder.drawTable(50, y + 25, headerTitles, data, columnWidths);

        paint.setFakeBoldText(true);
        paint.setTextSize(10);
        canvas.drawText("点位平均值", 50,  SecondY + 15, paint);
        paint.setTextSize(8);
        paint.setTextAlign(Paint.Align.LEFT);
        String[][] tableData = getLoctionStatsTable(stats);
        paint.setFakeBoldText(false);
        float v = pdfPageBuilder.drawTableWithoutBorder(50, SecondY + 15, tableData, columnWidths);


        paint.setTextSize(10);
        paint.setFakeBoldText(true);
        canvas.drawText("详细数据", 50,  v + 15, paint);

        paint.setTextSize(8);
        //  文本X坐标
        textX = textX - 45;
        // 绘制“阈值”标签及其前面的黄色小正方形
        paint.setColor(Color.YELLOW);
        canvas.drawRect(textX, v + 7, textX+10, v + 17, paint); // 黄色小正方形
        paint.setColor(Color.BLACK);
        canvas.drawText("报警水平", textX+12, v + 15, paint);
        paint.setColor(Color.RED);

        canvas.drawRect(textX+62, v + 7, textX+70, v + 17, paint); // 红色小正方形
        paint.setColor(Color.BLACK);
        canvas.drawText("行动限", textX+72, v + 15, paint);

        //时间范围
        //avgMeasure.avgMeasurement.getStartTime() 加一分钟
        String dateStr = avgMeasure.avgMeasurement.getStartTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paint.setFakeBoldText(false);
        try {
            Date date = sdf.parse(dateStr); // 可能抛出 ParseException
            // 使用 Calendar 增加一分钟
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MINUTE, 1); // 加1分钟
            // 格式化回字符串
            String newDateStr = sdf.format(calendar.getTime());

            canvas.drawText("时间范围：" + dateStr + " ~ " + newDateStr, 50, v + 30, paint);
        } catch (ParseException e) {
            System.err.println("日期格式错误！请使用 yyyy-MM-dd HH:mm:ss 格式");
            e.printStackTrace();
        }
        canvas.drawText("计数单位  ∑/m³", textX +40, v + 30, paint);

        y = v + 40;
        float[] CountWidths = {25, 25, 50, 50, 40, 50, 50,50,50,50,50}; // 每列的宽度
        // 表格标题
        String[] headerCountTitle = {"编号","ID","起始时间","位点","体积", "0.5μm", "1.0μm", "2.0μm", "3.0μm", "5.0μm", "10μm"};
        //详细数据
        String[][] testdata = getTableDataFromMeasurements(avgMeasure.measurements);

        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, y , 50 + sum(CountWidths), y + 17, paint); // 画表头背景
        paint.setColor(Color.BLACK);
        //开始画表格
        float v1 = pdfPageBuilder.drawTable(50, y, headerCountTitle, testdata, CountWidths);

        y = v1 + 55;
        return y;
    }
    //获取所有测试的数据
    private String[][] getTableDataFromMeasurements(List<Measurement> measurements) {
        if(measurements == null){
            return new String[0][0];
        }
        String[][] tableData = new String[measurements.size()][11];
        for (int i = 0; i < measurements.size(); i++) {
            Measurement data = measurements.get(i);
            tableData[i][0] = String.valueOf(i+1);
            tableData[i][1] =  String.valueOf(data.getId());
            tableData[i][2] = data.getStartTime();
            tableData[i][3] = String.valueOf(data.getNotes());
            tableData[i][4] = String.valueOf(data.getFlowRate());
            tableData[i][5] = String.valueOf(data.getValue05());
            tableData[i][6] = String.valueOf(data.getValue10());
            tableData[i][7] = String.valueOf(data.getValue20());
            tableData[i][8] = String.valueOf(data.getValue30());
            tableData[i][9] = String.valueOf(data.getValue50());
            tableData[i][10] = String.valueOf(data.getValue100());
        }
        return tableData;
    }

    //获取位点平均数据
    private String[][] getLoctionStatsTable(List<LocationStats> stats) {
        if (stats == null || stats.isEmpty()) {
            return new String[0][0];
        }
        List<String[]> tableRows = new ArrayList<>();
        for (LocationStats s : stats) {
            String[] row = new String[7];
            row[0] = s.getLocationName();
            row[1] = s.getAvg05()  + "";
            row[2] = s.getAvg10()  + "";
            row[3] = s.getAvg20()  + "";
            row[4] = s.getAvg30()  + "";
            row[5] = s.getAvg50()  + "";
            row[6] = s.getAvg100() + "";
            tableRows.add(row);
        }
        return tableRows.toArray(new String[0][0]);
    }

   //获取统计分析数据
    private String[][] convertToTableData(List<SizeStats> statRows,  String[] allCounts) {
        if (statRows == null || statRows.isEmpty() || allCounts == null || allCounts.length == 0) {
            return new String[0][0];
        }

        String[][] data = new String[6][allCounts.length + 1];


        // 填充每个粒径的数据
        for (int i = 0; i < allCounts.length; i++) {
            SizeStats stats = statRows.get(i);
            String sizeName = allCounts[i];

            // 设置第一列的统计指标名称
            data[i][0] = sizeName;

            // 表头（第一行）是粒径名称
            data[0][i + 1] = String.valueOf(stats.getAvg());
            // 填充统计值
            data[1][i + 1] = String.valueOf(stats.getSd());
            data[2][i + 1] = String.valueOf(stats.getSe());
            data[3][i + 1] = "——";
            data[4][i + 1] = String.valueOf(stats.getMax());
            data[5][i + 1] = String.valueOf(stats.getMAX_LOC());
        }

        return data;
    }

    //采样设置
    private float drawAdditionalContent(Canvas canvas, float startY,List<LocationStats> stats) {
        Paint paint = createPaint(10, Color.BLACK, false);
        paint.setTypeface(font);

        // 1. 添加标题
        paint.setFakeBoldText(true);
        canvas.drawText("采样设置", 50, startY + 10, paint);
        paint.setTextSize(8);
        // 2. 绘制表头
        String[] headerTitles = {
                "位点", "延迟", "间隔", "采样时间", "体积(L)", "次数",
                "采样时间", "体积(L)", "次数"
        };

        // 表头背景颜色
        paint.setColor(0xFFF2F2F2);
        canvas.drawRect(50, startY + 20, 595 - 50, startY + 50, paint);

        // 表头文本颜色
        paint.setColor(Color.BLACK);
        paint.setTextAlign(Paint.Align.CENTER);


        // 表头列宽
        float[] columnWidths = {65, 55, 55, 55, 50, 50, 55, 55, 55};

        // 绘制表头文本
        float x = 50;
        for (int i = 0; i < headerTitles.length; i++) {
            if(i>2){
                canvas.drawText(headerTitles[i], x + columnWidths[i] / 2, startY + 44, paint);
                x += columnWidths[i];
                if(i == 3){
                    canvas.drawText("预置值", (x + columnWidths[i] / 2)-5, startY + 32, paint);
                } else if (i == 6) {
                    canvas.drawText("实际值", (x + columnWidths[i] / 2)-5, startY + 32, paint);
                }
            }else{
                canvas.drawText(headerTitles[i], x + columnWidths[i] / 2, startY + 36, paint);
                x += columnWidths[i];
            }
        }
        paint.setFakeBoldText(false);
        // 3. 绘制表体
        String[][] tableData = generateTableDataFromMeasurements(stats);

        // 表体行高
        float rowHeight = 30;

        // 绘制表体数据
        float y = startY + 40; // 从表头下方开始
        for (String[] rowData : tableData) {
            x = 50;
            for (int i = 0; i < rowData.length; i++) {
                canvas.drawText(rowData[i], x + columnWidths[i] / 2, y + rowHeight - 7, paint);
                x += columnWidths[i];
            }
            y += rowHeight -13;
        }
        //取消字体居中
        paint.setTextAlign(Paint.Align.LEFT);
        //绘制斜体
        paint.setTypeface(Typeface.create(font, Typeface.ITALIC));
        canvas.drawText("注意:    采样时间和体积的实际值取所有循环中的最小值。",50,  y+ 20, paint);

        // 4. 返回最后使用的Y坐标
        return y+25;  // 返回表体最后一行的Y坐标
    }


    // 绘制页眉 - 返回新的Y坐标
    private float drawHeader(Canvas canvas, PdfDocument.PageInfo pageInfo, float startY) {
        Paint paint = createPaint(16, Color.BLACK, true);
        paint.setTypeface(font);

        // 绘制Logo
        Drawable vectorDrawable = ContextCompat.getDrawable(context, R.drawable.logo_svg);
        if (vectorDrawable != null) {
            int desiredWidth = 80;
            int desiredHeight = (int) (desiredWidth * (float) vectorDrawable.getIntrinsicHeight() / vectorDrawable.getIntrinsicWidth());
            int scaleFactor = 2;
            Bitmap bitmap = Bitmap.createBitmap(desiredWidth * scaleFactor, desiredHeight * scaleFactor, Bitmap.Config.ARGB_8888);
            Canvas tempCanvas = new Canvas(bitmap);
            vectorDrawable.setBounds(0, 0, tempCanvas.getWidth(), tempCanvas.getHeight());
            vectorDrawable.draw(tempCanvas);
            canvas.drawBitmap(bitmap,
                    new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
                    new Rect(50, 20, 50 + desiredWidth, 20 + desiredHeight),
                    null);
        }

        // 绘制标题文本
        String text = "尘埃粒子计数器";
        float textWidth = paint.measureText(text);
        float textX = pageInfo.getPageWidth() - 50 - textWidth;
        canvas.drawText(text, textX, 25 + paint.getTextSize(), paint);

        // 绘制横线
        float lineY = 5 + paint.getTextSize() + 30;
        canvas.drawLine(50, lineY, pageInfo.getPageWidth() - 50, lineY, paint);

        // 返回新的Y坐标（横线下方）
        return lineY + 10; // 加10作为间距
    }

    // 绘制报告标题 - 返回新的Y坐标
    private float drawReportTitle(Canvas canvas, float startY) {
        Paint paint = createPaint(20, Color.BLACK, true);
        paint.setTypeface(font);

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float textHeight = fontMetrics.descent - fontMetrics.ascent;
        float textY = startY + paint.getTextSize();

        canvas.drawText("采样数据报告", 50, textY+15, paint);

        // 返回新的Y坐标（标题下方）
        return textY + textHeight + 10; // 加10作为间距
    }

    // 绘制设备信息 - 返回新的Y坐标
    private float drawDeviceInfo(Canvas canvas, PdfDocument.PageInfo pageInfo, float startY) {
        Paint paint = createPaint(8, Color.BLACK, false);
        paint.setTypeface(Typeface.create(font, Typeface.ITALIC));

        String[] texts = {
                "设备型号   A240",
                "序列号      240070",
                "校准日期   2025-04-02",
                "设备ID      N/A"
        };

        float textWidth = paint.measureText("校准日期    2025-0402");
        float startX = pageInfo.getPageWidth() - 50 - textWidth;
        float textY = startY - 50;

        for (String line : texts) {
            canvas.drawText(line, startX, textY, paint);
            textY += 15;
        }

        // 返回设备信息区域底部Y坐标
        return Math.max(startY + (texts.length * 4), startY );
    }

    // 绘制报告内容
    private float drawReportContent(Canvas canvas, float startY,AvgMeasurementWithMeasurements avgMeasure) {
        Paint paint = createPaint(12, Color.BLACK, true);
        paint.setTypeface(font);

        // 报告标题
        drawLabelValuePair(canvas, "报告标题", title, 50, startY, paint);

        // 结果
        paint.setFakeBoldText(true);
        drawLabelValuePair(canvas, "结果", "完成", 50, startY + 20, paint);
        paint.setFakeBoldText(false);

        // 用户信息
        drawMultiColumnInfo(canvas,
                new String[]{"用户", "群组", "程序"},
                new String[]{avgMeasure.user.getName(), avgMeasure.location.getGroup(), "规范"},
                50, startY + 35, 150);

        // 其他信息...
        drawMultiColumnInfo(canvas,
                new String[]{"流速", "区域", "气体"},
                new String[]{avgMeasure.avgMeasurement.getFlow()  + "LPM", avgMeasure.location.getName(), avgMeasure.avgMeasurement.getExtra1()},
                50, startY + 46, 150);

        drawMultiColumnInfo(canvas,
                new String[]{"方法", "状态", "法规"},
                new String[]{"Default", "动态", avgMeasure.avgMeasurement.getLaws()},
                50, startY + 56, 150);

        float lastY = startY + 70;  // 根据实际内容调整这个值

        // 3. 返回最后使用的Y坐标
        return lastY;
    }

    private String[][] generateTableDataFromMeasurements(List<LocationStats> stats) {
        if (stats == null || stats.isEmpty()) {
            return new String[0][0];
        }
        List<String[]> tableRows = new ArrayList<>();
        for (LocationStats s : stats) {
            String[] row = new String[9];
            row[0] = s.getLocationName();
            row[1] = "00:00:02";
            row[2] = "00:00:05";
            row[3] = "00:01:00";
            row[4] = s.getFlow() + "LPM";
            row[5] = s.getCount()+"";
            row[6] = "00:01:00";
            row[7] = s.getFlow() + "LPM";
            row[8] = s.getCount()+"";
            tableRows.add(row);
        }
        return tableRows.toArray(new String[0][0]);
    }
    //辅助方法：计算列宽总和
    private float sum(float[] array) {
        float total = 0;
        for (float value : array) {
            total += value;
        }
        return total;
    }

    // 辅助方法：创建Paint对象
    private Paint createPaint(float textSize, int color, boolean isBold) {
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setTextSize(textSize);
        paint.setFakeBoldText(isBold);
        return paint;
    }

    // 辅助方法：绘制标签-值对
    private void drawLabelValuePair(Canvas canvas, String label, String value, float x, float y, Paint paint) {
        canvas.drawText(label, x, y, paint);
        boolean wasBold = paint.isFakeBoldText();
        paint.setFakeBoldText(false);
        canvas.drawText(value, x + paint.measureText(label + "   "), y, paint);
        paint.setFakeBoldText(wasBold);
    }

    // 辅助方法：绘制多列信息
    private void drawMultiColumnInfo(Canvas canvas, String[] labels, String[] values, float startX, float startY, float columnWidth) {
        Paint paint = createPaint(8, Color.BLACK, false);
        paint.setTypeface(font);

        for (int i = 0; i < labels.length; i++) {
            canvas.drawText(labels[i], startX + (i * columnWidth), startY, paint);
            canvas.drawText(values[i],
                    startX + (i * columnWidth) + paint.measureText(labels[i] + "       "),
                    startY, paint);
        }
    }


    //切换fragment方法
    private void loadFragment(Fragment fragment) {
        requireActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .addToBackStack(null)
                .commit();
    }
    //模拟添加测试记录
    private void addNewMeasurement() {
        // 假设我们已经从界面获取了这些值

        String startTime = currentTime;
        String endTime = currentTime.split(" ")[2];
        double flowRate = 100;
        int value05 = 5146;
        int value10 = 7445;
        int value20 = 2566;
        int value30 = 4485;
        int value50 = 774;
        int value100 = 3645;
        int value03 = 84725;

        AppDatabase.databaseWriteExecutor.execute(() -> {
            // 查找用户和位置ID

            viewModel.addNewMeasurement(
                    1,
                    startTime,
                    endTime,
                    flowRate,
                    value03,
                    value05,
                    value10,
                    value20,
                    value30,
                    value50,
                    value100,
                    "loction1"
            );
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dialogs != null && dialogs.isShowing()) {
            dialogs.dismiss();
            dialogPrint.dismiss();
        }
    }
}